package com.tjyx.common.util;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 反射工具类
 * 时间：2012-3-26
 * 
 * @author zhutianjie
 * @version v1.0
 *
 */
public class ReflectUtil {

	/**
	 * 字符串"get"
	 */
	private static final String GET = "get";
	/**
	 * 字符串"set"
	 */
	private static final String SET = "set";
	
	/**
	 * 将字符串转换为get*的格式
	 * @param targetString 被转换的字符串
	 * @return
	 */
	public static String createGetMethodName(String targetString) {
		targetString = upperFirstChar(targetString);
		String getMethodName = GET + targetString;
		return getMethodName;
	}
	
	/**
	 * 将字符串转换为set*的格式
	 * @param targetString
	 * @return
	 */
	public static String createSetMethodName(String targetString) {
		targetString = upperFirstChar(targetString);
		String setMethodName = SET + targetString;
		return setMethodName;
	}
	
	/**
	 * 将字符串的首字母大写
	 * @param targetString
	 * @return
	 */
	public static String upperFirstChar(String targetString) {
		String firstChar = targetString.substring(0,1);
		String withOutFirstChar = targetString.substring(1);
		targetString = firstChar.toUpperCase() + withOutFirstChar;
		return targetString;
	}
	
	/**
	 * 创建字段的set*反射方法
	 * @param fieldName 字段名
	 * @param clazz 字段所属类
	 * @return
	 */
	public static Method createSetMethod(String fieldName, Class clazz) {
		Method setMethod = null;
		try {
			Field field = clazz.getDeclaredField(fieldName);
			String setMethodName = createSetMethodName(fieldName);
			Class fieldClass = field.getType();
			setMethod = clazz.getMethod(setMethodName, fieldClass);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchFieldException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return setMethod;
	}
	
	/**
	 * 创建字段的get*方法
	 * @param field
	 * @param clazz
	 * @return
	 */
	public static Method createGetMethod(Field field, Class clazz) {
		Method getMethod = null;
		try {
			String fieldName = field.getName();
			String getMethodName = createGetMethodName(fieldName);
			getMethod = clazz.getMethod(getMethodName);
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		return getMethod;
	}
}
